using imitateMacQQ.WebApi.Repository.EFCore.Model.utils;
using imitateMacQQ.WebApi.Repository.Redis.Interface;

namespace imitateMacQQ.WebApi.Repository.Redis;

public class TestHostedService : IHostedService, IDisposable
{
    private Timer? _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _redisLinkSql.CacheInfoRedis();
        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
        //定时任务
        return Task.CompletedTask;
    }

    private readonly ISqlLinkRedis _redisLinkSql;
    private readonly UtilsTime _utilsTime;

    public TestHostedService(ISqlLinkRedis redis, RedisHelper redisHelper, UtilsTime utilsTime
    )
    {
        _utilsTime = utilsTime;
        var redis1 = redisHelper.GetDatabase();
        _redisLinkSql = redis;
        RedisProtect.Redis_Initialization(redis1);
    }

    private void DoWork(object? state)
    {
        _redisLinkSql.CacheInfoRedis(); //刷新redis
        if (DateTime.Now.Hour.ToString() +
            DateTime.Now.Minute.ToString() == "1212")
        {
            _utilsTime.DelEndTimePhone();
        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _redisLinkSql.ClearRedisData(); //定时任务结束 关闭redis缓存
        return Task.CompletedTask;
    }


    public void Dispose()
    {
        _timer?.Dispose();
    }
}